import { defineStore } from "pinia";
import api from "@/api";
import { showToast } from "vant";

// 最大同时轮询任务数
const MAX_CONCURRENT_POLLING = 3;

export const usePollingStore = defineStore("polling", {
  state: () => ({
    // 存储所有轮询任务的状态，以 taskNo 为 key
    pollingTasks: new Map(),
    // 存储已完成任务的结果
    completedTasks: new Map(),
    // 最近完成的任务
    latestCompletedTask: null // { taskNo: string, imgUrl: string }
  }),
  actions: {
    // 启动轮询任务
    startPolling(params) {
      const taskNo = params.taskNo;
      if (!taskNo) {
        showToast("taskNo is required for polling")
        return;
      }

      // 检查是否已存在相同 taskNo 的任务
      if (this.pollingTasks.has(taskNo)) {
        console.warn(`Polling task ${taskNo} already exists`);
        return;
      }

      // 检查当前轮询任务数量
      if (this.pollingTasks.size >= MAX_CONCURRENT_POLLING) {
        showToast("The maximum number of tasks has been reached");
        return;
      }

      // 初始化任务状态
      const taskState = {
        imgUrl: "",
        isPolling: true,
        retryCount: 0,
        targetStatus: 60,
        timeoutId: null,
        startTime: Date.now(),
        isPollFail: false,
        pollingTimer: null,
        taskNo: taskNo,
        taskType: null
      };

      // 将新任务添加到 Map
      this.pollingTasks.set(taskNo, taskState);

      // 设置超时定时器（2分钟）
      taskState.timeoutId = setTimeout(() => {
        this._handleTimeout(taskNo);
      }, 120000);

      // 执行首次请求并启动轮询
      const execute = async () => {
        try {
          const res = await api.taskInfo(params);
          
          // 获取当前任务最新状态（防止多次调用导致状态不一致）
          const currentTask = this.pollingTasks.get(taskNo);
          if (!currentTask || !currentTask.isPolling) return;

          if (res.data.status === currentTask.targetStatus) {
            currentTask.imgUrl = res.data.resultFileUrl;
            currentTask.taskType = res.data.taskType;
            this.stopPolling(taskNo);
          } else if (res.code !== 200) {
            this._handleRetry(taskNo);
          }
        } catch (err) {
          this._handleRetry(taskNo);
        }
      };

      // 启动轮询
      execute();
      taskState.pollingTimer = setInterval(execute, 5000);
    },

    // 停止指定轮询任务
    stopPolling(taskNo) {
      const task = this.pollingTasks.get(taskNo);
      if (!task || !task.isPolling) return;

      clearInterval(task.pollingTimer);
      clearTimeout(task.timeoutId);

      // 保存结果到 completedTasks
      this.completedTasks.set(taskNo, {
        imgUrl: task.imgUrl,
        isPollFail: task.isPollFail,
        isPolling: task.isPolling,
        taskNo: task.taskNo,
        taskType: task.taskType
      });
      
      // 更新任务状态
      task.isPolling = false;
      task.pollingTimer = null;
      task.timeoutId = null;

      // 如果是成功完成的任务（有图片URL），记录为最新任务
      if (task.imgUrl && !task.isPollFail) {
        this.latestCompletedTask = {
          taskNo,
          imgUrl: task.imgUrl,
          taskType: task.taskType
        };
      }

      // 从 Map 中移除任务
      this.pollingTasks.delete(taskNo);
    },

    // 获取最新完成的任务
    getLatestCompletedTask() {
      return this.latestCompletedTask;
    },

    // 清除最新任务
    clearLatestCompletedTask() {
      this.latestCompletedTask = null;
    },

    // 获取任务结果（包含已完成任务）
    getTaskResult(taskNo) {
      // 优先从轮询中获取
      if (this.pollingTasks.has(taskNo)) {
        return this.pollingTasks.get(taskNo);
      }
      // 从已完成任务获取
      if (this.completedTasks.has(taskNo)) {
        return this.completedTasks.get(taskNo);
      }
      return null;
    },

    // 新增：清理已完成任务
    cleanupCompletedTask(taskNo) {
      this.completedTasks.delete(taskNo);
    },

    // 错误重试策略
    _handleRetry(taskNo) {
      const task = this.pollingTasks.get(taskNo);
      if (!task) return;

      if (task.retryCount < 3) {
        task.retryCount++;
      } else {
        task.isPollFail = true;
        showToast("Exceeding the maximum number of retries");
        this.stopPolling(taskNo);
      }
    },

    // 超时处理
    _handleTimeout(taskNo) {
      const task = this.pollingTasks.get(taskNo);
      if (!task) return;

      task.isPollFail = true;
      showToast("request timeout");
      this.stopPolling(taskNo);
    },

    // 获取任务状态（供外部调用）
    getTaskState(taskNo) {
      return this.pollingTasks.get(taskNo) || null;
    },

    // 停止所有轮询任务
    stopAllPolling() {
      this.pollingTasks.forEach((_, taskNo) => {
        this.stopPolling(taskNo);
      });
    }
  },
});